package com.z_talk.server.core;

import com.z_talk.core.enums.RequestEnum;
import com.z_talk.core.message.RequestMessage;
import com.z_talk.core.model.LoginModel;
import com.z_talk.core.model.PrivateTalkModel;
import com.z_talk.core.model.UserInfo;
import com.z_talk.core.vo.LoggerVO;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.io.IOException;


public class ServerHandler extends ChannelHandlerAdapter {

    @Override
    // 消息传入读取消息
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RequestMessage message = (RequestMessage)msg;
        RequestEnum messageType = message.getMessageType();
        Channel channel = ctx.channel();
        switch (messageType){
            case REGISTER_REQUEST:
                UserInfo userInfo = (UserInfo) message.getAttribute().get(RequestEnum.REGISTER_REQUEST.getAttr());
                MessageHandler.regiterHandler(channel,userInfo);
                break;
            case LOGIN_REQUEST:
                LoginModel loginVO = (LoginModel) message.getAttribute().get(RequestEnum.LOGIN_REQUEST.getAttr());
                MessageHandler.loginHandler(channel,loginVO);
                break;
            case WORLD_TALK_REQUEST:
                String worldTalk = (String) message.getAttribute().get(RequestEnum.WORLD_TALK_REQUEST.getAttr());
                MessageHandler.sendWorldTalk(channel,worldTalk);
                break;
            case PRIVATE_TALK_REQUEST:
                PrivateTalkModel privateTalkModel = (PrivateTalkModel) message.getAttribute().get(RequestEnum.PRIVATE_TALK_REQUEST.getAttr());
                MessageHandler.sendPrivateTalk(channel,privateTalkModel);
                break;
            default:
                LoggerVO loggerVO = new LoggerVO("收到一条未知消息-"+message.getMessageType().getMessageType());
                ServerMain.serverView.updateLogger(loggerVO.getLogger());
                break;
        }
    }

    // 在channel结束生命周期时调用
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        MessageHandler.logoutHandler(channel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if ("远程主机强迫关闭了一个现有的连接。".equals(cause.getMessage())&&cause instanceof IOException){
            return;
        }
        super.exceptionCaught(ctx, cause);
    }


}
